import Vue from 'vue'
import VueRouter from 'vue-router'

// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import util from '@/utils/util.js'
import store from '@/store/index'

// 路由数据
import routes from './routes'

// 固定菜单与路由
// import menuHeader from '@/menu/header'
// import menuAside from '@/menu/aside'
import { frameInRoutes } from '@/router/routes'
import layoutHeaderAside from '@/layout/header-aside'

import userService from "@/api/sys/user";

Vue.use(VueRouter)

// 导出路由 在 main.js 里使用
const router = new VueRouter({
	routes
})

let permissionMenu, permissionRouter = []

let permission = {
  functions: [],
  roles: [],
  isAdmin: false
}

//标记是否已经拉取权限信息
let isFetchPermissionInfo = false

let fetchPermissionInfo = async () => {
	//处理动态添加的路由
	const formatRoutes = function (routes) {
		routes.forEach(route => {
			//route.component = routerMapComponents[route.component];
			if (route.component == 'layoutHeaderAside') {
				route.component = layoutHeaderAside;
			}else{
				route.component = function (resolve) {
					require([`@/pages/${route.component_path}`], resolve)
				}
			}
			if (route.children) {
				formatRoutes(route.children)
			}
		})
	}

	try {
		let userPermissionInfo = await userService.getUserPermissionInfo()
		permissionMenu = userPermissionInfo.accessMenus
		permissionRouter = userPermissionInfo.accessRoutes
		permission.functions = userPermissionInfo.userPermissions
		permission.roles = userPermissionInfo.userRoles
		permission.interfaces = util.formatInterfaces(userPermissionInfo.accessInterfaces)
		permission.isAdmin = userPermissionInfo.isAdmin == 1
	} catch (ex) {
		console.log(ex)
	}

	//组合代码生成器生成的菜单和路由
	// permissionMenu = [...permissionMenu, ...autoGenerateMenusAndRouters.menus]
	// permissionRouter = [...permissionRouter, ...autoGenerateMenusAndRouters.routers]

	formatRoutes(permissionRouter)
	// let allMenuAside = [...menuAside, ...permissionMenu]
	// let allMenuHeader = [...menuHeader, ...permissionMenu]
	let allMenuAside = permissionMenu
	let allMenuHeader = permissionMenu

	//动态添加路由
	//router.addRoutes(permissionRouter);

	// 处理路由 得到每一级的路由设置
	store.commit('page/init', [...frameInRoutes, ...permissionRouter])
	// 设置顶栏菜单
	store.commit('menu/headerSet', allMenuHeader)
	// 设置侧边栏菜单
	store.commit('menu/fullAsideSet', allMenuAside)
	// 初始化菜单搜索功能
	store.commit('search/init', allMenuHeader)
	// 设置权限信息
	store.commit('permission/set', permission)
	// 加载上次退出时的多页列表
	store.dispatch('page/openedLoad')
	await Promise.resolve()
}

//免校验token白名单
let whiteList = ['/login']

/**
 * 路由拦截
 * 权限验证
 */
router.beforeEach(async (to, from, next) => {
	// 进度条
	NProgress.start()
	// 关闭搜索面板
	store.commit('search/set', false)
	// 这里暂时将cookie里是否存有token作为验证是否登录的条件
	// 请根据自身业务需要修改
	const token = util.cookies.get('access_token')
	if (whiteList.indexOf(to.path) === -1) {
		if (token && token !== 'undefined') {
			//拉取权限信息
			if (!isFetchPermissionInfo) {
				await fetchPermissionInfo();
				isFetchPermissionInfo = true;
				next(to.path, true)
			} else {
				next()
			}
		}else{
			// 没有登录的时候跳转到登录界面
			// 携带上登陆成功之后需要跳转的页面完整路径
			util.cookies.set('redirect', to.fullPath)
			next({
				name: 'login',
			})
			// https://github.com/d2-projects/d2-admin/issues/138
			NProgress.done()
		}
	}else{
		if (to.name === 'login') {
			// 如果已经登录，则直接进入系统
			if (token && token !== undefined) {
				next(from.path, true);
				NProgress.done()
			} else {
				next()
			}
		} else {
			next()
		}
	}
})


router.afterEach(to => {
	// 进度条
	NProgress.done()
	// 多页控制 打开新的页面
	store.dispatch('page/open', to)
	// 更改标题
	util.title(to.meta.title)
})

export default router